package com.security.config.security.authentication.sms;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.security.web.util.matcher.RequestMatcher;

/**
 * 短信验证码认证过滤
 * 调用 AuthenticationManager.authenticate() 方法进行认证
 *
 * @author DblSun
 */
public class SmsAuthenticationFilter extends AbstractAuthenticationProcessingFilter {

    public SmsAuthenticationFilter(RequestMatcher requiresAuthenticationRequestMatcher,
                                   AuthenticationManager authenticationManager) {
        super(requiresAuthenticationRequestMatcher, authenticationManager);
    }

    @Override
    public Authentication attemptAuthentication(HttpServletRequest request,
                                                HttpServletResponse response) throws AuthenticationException {
        String phone = request.getParameter("phone");
        String captcha = request.getParameter("captcha");
        SmsAuthenticationToken smsAuthenticationToken = new SmsAuthenticationToken(phone, captcha);
        return this.getAuthenticationManager().authenticate(smsAuthenticationToken);
    }
}
